<?php
/**
 *      [迷你云] (C)2009-2012 南京恒为网络科技.
 *   软件仅供研究与学习使用，如需商用，请访问www.miniyun.cn获得授权
 * 
 */
?>
<?php


class AlbumList extends FillBase {
    
    public function obtainAlbumList($user_id, $limit = 45, $start = 0, $cid) {
        $data = array();
        if($cid == -1) {             $pdi = UserFile::model()->findAllBySql("SELECT DISTINCT (parent_file_id) AS parent_file_id FROM  " . Yii::app()->params['tablePrefix'] . "files WHERE (user_id =$user_id and is_deleted!=1 AND version_id in(select id from " . Yii::app()->params['tablePrefix'] . "file_versions where mime_type like 'image%')) ORDER BY created_at desc limit " . $start . ", " . $limit);
            foreach($pdi as $value) {
                $array = Array();
                if($value['parent_file_id'] == 0) {
                    $array['id'] = 0;
                    $array['file_type'] = 1;
                    $array['parent_file_id'] = "";
                    $array['file_name'] = "根目录";
                }else {
                    $file = UserFile::model()->findAllBySql("select * from " . Yii::app()->params['tablePrefix'] . "files where id = " . $value['parent_file_id']);
                    if(!empty($file)) {
                        $array['id'] = $file[0]['id'];
                        $array['file_type'] = $file[0]['file_type'];
                        $array['parent_file_id'] = $file[0]['parent_file_id'];
                        $array['file_name'] = $file[0]['file_name'];
                    }
                }
                array_push($data, $array);
            }
        }else {             $list = UserFile::model()->findAllBySql("SELECT * FROM " . Yii::app()->params['tablePrefix'] . "files WHERE user_id=" . $user_id . " and is_deleted != 1 and parent_file_id=" . $cid . " and version_id in(select id from " . Yii::app()->params['tablePrefix'] . "file_versions where mime_type like 'image%') ORDER BY created_at desc limit " . $start . ", " . $limit);
            $data = $this->filFillList($list);
        }
        return $data;
    }
    
    public function obtainAlbumListByLocation($user_id, $limit = 45, $start = 0, $ids) {
        $data = array();
        $list = UserFile::model()->findAllBySql("SELECT * FROM " . Yii::app()->params['tablePrefix'] . "files WHERE user_id=" . $user_id . " and is_deleted != 1 and version_id in (" . $ids . ") ORDER BY created_at desc limit " . $start . ", " . $limit);
        $data = $this->filFillList($list);
        return $data;
    }

    
    public function submitGpsinfos() {
                $map_enable = Yii::app()->params['app']['gpsEnable'];
        if(!$map_enable) {             return false;         }
        $user = Yii::app()->session["user"];
        $user_id = $user["id"];
        $support_types = array('jpg', 'jpeg');
        $data = array();
        $file = UserFile::model()->findAll("user_id=?  AND file_type=? AND is_deleted=?", array($user_id, 0, 0));
        if($file) {
            foreach($file as $value) {
                $version_id = $value['version_id'];                                                 $is_exit = FileExif::model()->find('version_id=:id', array(':id' => $version_id));                 if($is_exit) {                     continue;
                }
                                $path_parts = pathinfo($value['file_path']);
                if(!array_key_exists('extension', $path_parts)) {
                                    continue;
                }
                $extention = strtolower($path_parts['extension']);
                if(!in_array($extention, $support_types)) {
                                    continue;
                }
                                $file_version = FileVersion::model()->find("id=?", array($version_id));
                $signature = $file_version['file_signature'];
                $storePath = DOCUMENT_ROOT_BLOCK . CUtils::getPathBySplitStr($signature);

                $exif = $this->readPhotoFile($storePath);
                $latLng = $this->juedgeGps($exif);
                $exif = serialize($exif);
                $lat=null;
                $lng=null;
                if ($latLng){
                    $lat=$latLng['lat'];
                    $lng=$latLng['lng'];
                }
                                FileExif::model()->createFileExif($version_id, $lat, $lng, $exif);
            }
        }
        return true;
    }




    
    public function submitGps($file_path, $version_id) {

        $retval = null;
        $is_exit = FileExif::model()->find('version_id=:id', array(':id' => $version_id));         if($is_exit) {                         if(!$is_exit['longtitude'] || !$is_exit['latitude']) {
                return $retval;
            }
            return $is_exit['latitude'] . ',' . $is_exit['longtitude'];
        }

        $user = Yii::app()->session["user"];
        $user_id = $user['id'];
        $support_types = array('jpg', 'jpeg');

        $path_parts = pathinfo($file_path);
        if(!array_key_exists('extension', $path_parts)) {
                                            return $retval;
         }
                $extention = strtolower($path_parts['extension']); 
        if(!in_array($extention, $support_types)) {
                        return $retval;
        }
                        $file_version = FileVersion::model()->find("id=?", array($version_id));
        $file_signature = $file_version['file_signature'];

        $storePath = DOCUMENT_ROOT_BLOCK . CUtils::getPathBySplitStr($file_signature);
        
        $exif = $this->readPhotoFile($storePath);
        $latLng = $this->juedgeGps($exif);
        $lat=null;
        $lng=null;
        $exif = serialize($exif);
        if ($latLng){
            $lat=$latLng['lat'];
            $lng=$latLng['lng'];
            $retval = $latLng['lat'] . ',' . $latLng['lng'];
        }else{
            FileExif::model()->createFileExif($version_id, $latLng['lat'], $latLng['lng'], $exif);
            return $retval;
        }
               
        FileExif::model()->createFileExif($version_id, $latLng['lat'], $latLng['lng'], $exif);
                return $retval;
    }


    
    public function juedgeGps($exif){
        $lat_no = null;
        $lng_no = null;
        if(is_array($exif)) {             if(array_key_exists('GPS', $exif)) {                 if (!array_key_exists('GPSLatitudeRef', $exif['GPS'])){
                    return false;
                }
                $gps_lat_tag = $exif['GPS']['GPSLatitudeRef'];                 if (!array_key_exists('GPSLongitudeRef', $exif['GPS'])){
                    return false;
                }
                $gps_lng_tag = $exif['GPS']['GPSLongitudeRef'];                 
                if (empty($gps_lat_tag) || empty($gps_lng_tag)) {
                    return false;
                }
                
                                                                if (!array_key_exists('GPSLatitude', $exif['GPS'])){
                    return false;
                }
                $lat = $exif['GPS']['GPSLatitude'];                 if (empty($lat)){
                    return false;
                }
                foreach($lat as &$value) {
                    $value = explode('/', $value);
                    if(count($value) == 2) {
                        $value = $value[0] / $value[1];
                    }
                }
                $latNum = $lat[0] + $lat[1] / 60 + $lat[2] / 3600;
                                                                if (!array_key_exists('GPSLongitude', $exif['GPS'])){
                    return false;
                }
                $lng = $exif['GPS']['GPSLongitude'];
                if (empty($lng)){
                    return false;
                }
                foreach($lng as &$value) {
                    $value = explode('/', $value);
                    if(count($value) == 2) {
                        $value = $value[0] / $value[1];
                    }
                }
                $lngNum = $lng[0] + $lng[1] / 60 + $lng[2] / 3600;
                                                                if($gps_lat_tag == 'S') {
                    $latNum = 0 - $latNum;
                }
                if($gps_lng_tag == 'W') {
                    $lngNum = 0 - $lngNum;
                }
                $lat_no = round($latNum, 6);
                $lng_no = round($lngNum, 6);

                $latLng = array();
                $latLng["lat"] = $lat_no;
                $latLng["lng"] = $lng_no;
                return $latLng;
            }
        }
        return false;
    }


    
    public function getGpsByVersionId($version_id) {
        $file = array();
        $fileInfos = FileExif::model()->find('version_id=:version_id', array(':version_id' => $version_id));
        $file['lat'] = $fileInfos['latitude'];
        $file['lng'] = $fileInfos['longtitude'];
        $exifArray = array();
        $exifArray = unserialize($fileInfos['exif']);         if(array_key_exists('IFD0', $exifArray)) {
            if(array_key_exists('Make', $exifArray['IFD0'])) {                 $file['exif'] = $exifArray['IFD0']['Make'] . ',' . $exifArray['IFD0']['Model'];
            }
        }
        return $file;
    }
    
    public function getGpsInfosByRange($ne_lat, $ne_lng, $sw_lat, $sw_lng) {
        $user = Yii::app()->session["user"];
        $user_id = $user["id"];
        $sql = Yii::app()->db->createCommand("
        select a.version_id,a.id,b.latitude,b.longtitude FROM  " . Yii::app()->params['tablePrefix'] . "files as a 
        join " . Yii::app()->params['tablePrefix'] . "file_exifs as b ON a.version_id=b.version_id  
        where a.user_id=$user_id AND a.is_deleted = 0 AND a.file_type=0 AND b.latitude is not null AND b.latitude>$sw_lat 
        AND b.latitude<$ne_lat AND b.longtitude>$sw_lng AND b.longtitude<$ne_lng
        ");
        $gps_infos = $sql->queryAll();
        $gpsArray = array();
        foreach($gps_infos as $val) {
            $data = array();
            $data['version_id'] = $val['version_id'];
            $data['id'] = $val['id'];
            $data['lat'] = $val['latitude'];
            $data['lng'] = $val['longtitude'];
            array_push($gpsArray, $data);
        }
        return $gpsArray;
    }
    
    function readPhotoFile($path) {
        if(!file_exists($path)) {
                        return null;
        }
        $exif = @exif_read_data($path, 0, true);
        if($exif === false) {
            return null;
        }
        return $exif;
    }
    
    public function getPhotos($ne_lat, $ne_lng, $sw_lat, $sw_lng) {
        $ret = array();
        $photos = $this->getGpsInfosByRange($ne_lat, $ne_lng, $sw_lat, $sw_lng);         foreach($photos as $photo) {
            $ret[] = $photo;
        }
        return $ret;
    }
    
    public function albumCount($user_id, $cid) {
        if($cid == -1) {
            $data = UserFile::model()->countBySql("SELECT count(DISTINCT parent_file_id) FROM  " . Yii::app()->params['tablePrefix'] . "files  WHERE (user_id =" . $user_id . " and is_deleted!=1 AND version_id in(select id from " . Yii::app()->params['tablePrefix'] . "file_versions where mime_type like 'image%'))");
        }else {
            $data = UserFile::model()->countBySql("SELECT count(*) FROM " . Yii::app()->params['tablePrefix'] . "files WHERE user_id=" . $user_id . " and is_deleted != 1 and parent_file_id=" . $cid . " and version_id in(select id from " . Yii::app()->params['tablePrefix'] . "file_versions where mime_type like 'image%')");
        }
        return $data;
    }

    
    public function getMultilist($user_id, $limit = 45, $start = 0, $aid, $cid) {
        if($aid == 3) {
            
            $data = $this->getAlbumList($aid, $cid, $user_id, $limit, $start);
        }else {
            $Conditons = $this->getMultiType($aid);
            $params = array(':user_id' => $user_id);
            $condition = "user_id=:user_id and is_deleted != 1 and version_id in(select id from " . Yii::app()->params['tablePrefix'] . "file_versions where mime_type $Conditons)";
            $data = $this->getList($condition, $params, $limit, $start);
        }
        return $data;
    }

    public function getAlbumList($aid, $cid, $user_id, $limit, $start) {
        $data = array();
        if($cid == -1) {             $pdi = UserFile::model()->findAllBySql("SELECT DISTINCT (parent_file_id) AS parent_file_id FROM  " . Yii::app()->params['tablePrefix'] . "files WHERE (user_id =1 AND version_id in(select id from " . Yii::app()->params['tablePrefix'] . "file_versions where mime_type like 'image%') AND file_size !=0 and is_deleted != 1 )");
            foreach($pdi as $value) {
                if($value['parent_file_id'] == 0) {
                    $array = Array();
                    $array['id'] = 0;
                    $array['file_type'] = 1;
                    $array['parent_file_id'] = 0;
                    $array['file_update_time'] = "无效";
                    $array['file_name'] = "迷你云根目录";
                    $array['file_size'] = "无效";
                    $array['file_path'] = "根目录";
                }else {
                    $file = UserFile::model()->findAllBySql("select * from " . Yii::app()->params['tablePrefix'] . "files where id = " . $value['parent_file_id']);
                    $array = Array();
                    $array['id'] = $file[0]['id'];
                    $array['file_type'] = $file[0]['file_type'];
                    $array['parent_file_id'] = $file[0]['parent_file_id'];
                    $array['file_update_time'] = CUtils::getFormatTime($file[0]['file_update_time']);
                    $array['file_name'] = $file[0]['file_name'];
                    $array['file_size'] = CUtils::getFormatSize($file[0]['file_size']);
                    $array['file_path'] = $file[0]['file_path'];
                }
                array_push($data, $array);
            }
        }else {
            $files = UserFile::model()->findAllBySql("SELECT * FROM " . Yii::app()->params['tablePrefix'] . "files WHERE user_id=" . $user_id . " and is_deleted != 1 and parent_file_id=" . $cid . " and version_id in(select id from " . Yii::app()->params['tablePrefix'] . "file_versions where mime_type like 'image%')ORDER BY file_type desc");
            foreach($files as $value) {
                $array = Array();
                $array['id'] = $value['id'];
                $array['file_type'] = $value['file_type'];
                $array['parent_file_id'] = $value['parent_file_id'];
                $array['file_update_time'] = CUtils::getFormatTime($value['file_update_time']);
                $array['file_name'] = $value['file_name'];
                $array['file_size'] = CUtils::getFormatSize($value['file_size']);
                $array['file_path'] = $value['file_path'];
                array_push($data, $array);
            }
        }
        return $data;
    }

    
    public function navigation($user_id, $parent_file_id = -1) {
        $nav = Array();
        if($parent_file_id == -1) {
            return $nav;
        }

                if($parent_file_id == 0) {
            $data = Array();
            $data["id"] = 0;
            $data["fileName"] = "根目录";
            $data["parent_file_id"] = -1;

            array_push($nav, $data);
        }

        while($parent_file_id != 0) {
            $condition = "user_id=:user_id and is_deleted != 1 and id=:id";
            $params = array(':user_id' => $user_id, ':id' => $parent_file_id);
            $file = $this->find($condition, $params);
            if(empty($file) || $file['id'] == 0) {
                return array_reverse($nav);
            }
            $data = Array();
            $data["id"] = $file['id'];
            $data["fileName"] = CUtils::utf8Unicode($file['file_name']);
            $data["parent_file_id"] = $file['parent_file_id'];

            array_push($nav, $data);
            $parent_file_id = $file['parent_file_id'];
        }

        return array_reverse($nav);
    }

    
    public function isHaveGps() {
        $user = Yii::app()->session["user"];
        $user_id = $user["id"];
        $sql = Yii::app()->db->createCommand("select *  FROM  " . Yii::app()->params['tablePrefix'] . "file_exifs where
         version_id in ( select version_id FROM " . Yii::app()->params['tablePrefix'] . "files where user_id=$user_id AND is_deleted = 0 AND file_type=0 ) 
         AND latitude!='' ");
        $gps_infos = $sql->queryAll();
        if(empty($gps_infos)) {
            return 0;
        }
        return 1;
    }
}
?>